<template>
  <div class="equipment">
    <Search @sendInfo="receiveInfo" :searchTitle="'设备编号:'" />
    <div class="list">
      <el-row>
        <el-col :span="4"
          ><el-button icon="iconfont icon-jiahao" type="warning" @click="newCreateEquit"
            >新建</el-button
          ><el-button type="info" @click="moreOperation">批量操作</el-button></el-col
        >
      </el-row>
      <el-table
        ref="singleTable"
        :data="equipmentInfo.currentPageRecords"
        highlight-current-row
        center
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column align="center" label="序号" type="index" width="150" height="45">
        </el-table-column>
        <el-table-column align="center" property="innerCode" label="设备编号"> </el-table-column>
        <el-table-column align="center" property="type.name" label="设备型号"> </el-table-column>
        <el-table-column align="center" property="node.name" label="详细地址"></el-table-column>
        <el-table-column align="center" property="ownerName" label="合作商"></el-table-column>
        <el-table-column align="center" label="设备状态">
          <template v-slot="{ row: { vmStatus } }">
            <!-- 获取的对象中属性,可变,应该使用对象属性的key.不可变直接 对象.属性 -->
            <div>{{ creatTypeNum[+vmStatus] || '未知' }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="450">
          <template slot-scope="{ row }">
            <el-button type="info" icon="el-icon-search" size="mini" @click.native="resource(row)"
              >货道</el-button
            >
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-magic-stick"
              @click.native="policy(row)"
              >策略</el-button
            >
            <el-button type="warning" icon="el-icon-edit" size="mini" @click.native="editInfo(row)"
              >修改</el-button
            ></template
          >
        </el-table-column>
      </el-table>
      <Pagination
        :searchTaskList="equipmentInfo"
        @currentSizeChange="(value) => (equipmentInfoParams.pageSize = value)"
        @currentPageChange="(value) => (equipmentInfoParams.pageIndex = value)"
      />
    </div>
    <!-- 新建 -->
    <Dialog :dialogVisibleInfo="dialogVisibleCreate" @dialogClose="dialogCloseCreate">
      <template #body>
        <el-form
          ref="ruleFormEdit"
          :model="ruleFormEquip"
          :rules="rulesEquip"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="设备编号">
            <template> 系统自动生成 </template>
          </el-form-item>
          <el-form-item label="选择型号:" prop="vmType">
            <el-select v-model="ruleFormEquip.vmType" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in vmTypeList"
                :key="item.typeId"
                :label="item.name"
                :value="item.typeId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择点位:" prop="nodeId">
            <el-select v-model="ruleFormEquip.nodeId" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in nodeIdList"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="confirm">
            <el-button type="primary" @click="submitForm">确认</el-button>
            <el-button @click="dialogVisibleCreate.dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
    <!-- 批量操作 -->
    <Dialog :dialogVisibleInfo="dialogVisibleOperation" @dialogClose="dialogCloseOperation"
      ><template #body>
        <el-form label-width="100px" class="demo-ruleForm">
          <el-form-item label="策略选择:">
            <el-select v-model="policyValue" placeholder="请选择" style="width: 100%" clearable>
              <el-option
                v-for="item in policyList"
                :key="item.policyId"
                :label="item.policyName"
                :value="item.policyId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="confirm">
            <el-button type="primary" @click="submitPolicy">确认</el-button>
            <el-button @click="dialogVisibleOperation.dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </template></Dialog
    >
    <!-- 策略管理 -->
    <Dialog :dialogVisibleInfo="dialogVisiblePolicy">
      <template #body>
        <div class="partnercontent">
          <div class="text">
            <p>机器编号:</p>
            <span>{{ policyDetails.innerCode }}</span>
          </div>
          <div class="text">
            <p>策略名称:</p>
            <span>{{ policyDetails.policyName }}</span>
          </div>
          <div class="text">
            <p>策略方案:</p>
            <span>{{ policyDetails.discount + '%' }}</span>
          </div>
        </div>
      </template>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="warning" size="small" plain @click.native="canclePolicy"
            >取消策略</el-button
          >
        </el-row>
      </template>
    </Dialog>
    <!-- 修改 -->
    <Dialog :dialogVisibleInfo="dialogVisibleEdit">
      <template #body>
        <el-form label-width="100px" class="demo-ruleForm">
          <el-form-item label="机器编号:">
            <template>{{ policyEdit.innerCode }} </template>
          </el-form-item>
          <el-form-item label="供货时间:">
            <template>{{ policyEdit.lastSupplyTime }} </template>
          </el-form-item>
          <el-form-item label="设备类型:">
            <template>{{ policyEdit.type.name }} </template>
          </el-form-item>
          <el-form-item label="设备容量:">
            <template>{{ policyEdit.type.channelMaxCapacity }} </template>
          </el-form-item>
          <el-form-item label="设备点位:" prop="nodeId">
            <el-select v-model="policyEdit.node.id" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in nodeIdList"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="合作商:">
            <template>{{ policyEdit.ownerName }} </template>
          </el-form-item>
          <el-form-item label="所属区域:">
            <template>{{ policyEdit.region.name }} </template>
          </el-form-item>
          <el-form-item label="设备地址:">
            <template>{{ policyEdit.node.addr }} </template>
          </el-form-item>
          <el-form-item class="confirm">
            <el-button type="primary" @click="submitEdit">确认</el-button>
            <el-button @click="dialogVisibleEdit.dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
    <GoodsChannel @refreshPage="refreshPage" />
  </div>
</template>

<script>
import {
  searchEquipmentAPI,
  getPolicyAPI,
  vmTypeAPI,
  nodeSearchAPI,
  addEquipmentAPI,
  applyPolicyAPI,
  policySearchAPI,
  cancelPolicyAPI,
  repairPolicyNodeAPI
} from '@/api'
// 引入货道组件
import GoodsChannel from './components/GoodsChannel'
export default {
  name: 'Equipment',
  components: {
    GoodsChannel
  },
  data() {
    return {
      // 搜索内容
      innerCode: null,
      // 获取合作商数据的参数
      equipmentInfoParams: {
        pageIndex: 1,
        pageSize: 10,
        status: null
      },
      // 新建的参数
      ruleFormEquip: {
        vmType: '',
        nodeId: ''
      },
      // 创建者id
      createUserId: 1,
      // 校验
      rulesEquip: {
        vmType: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
        nodeId: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      // 型号列表
      vmTypeList: [],
      // 点位列表
      nodeIdList: [],
      // 渲染设备列表
      equipmentInfo: {
        currentPageRecords: []
      },
      // 新建的弹窗
      dialogVisibleCreate: {
        dialogTitle: '新增设备',
        dialogVisible: false,
        dialogWidth: '30%'
      },
      // 修改的弹窗
      dialogVisibleEdit: {
        dialogTitle: '修改设备',
        dialogVisible: false,
        dialogWidth: '30%'
      },
      // 批量操作的弹框
      dialogVisibleOperation: {
        dialogTitle: '批量策略管理',
        dialogVisible: false,
        dialogWidth: '30%'
      },
      // 策略管理的弹框
      dialogVisiblePolicy: {
        dialogTitle: '策略管理',
        dialogVisible: false,
        dialogWidth: '30%'
      },
      // 详情的数据回显
      policyDetails: {
        innerCode: '',
        policyName: '',
        discount: '',
        policyId: ''
      },
      // 修改的数据回显
      policyEdit: {
        id: '',
        innerCode: '',
        lastSupplyTime: '',
        type: {
          name: '',
          channelMaxCapacity: ''
        },
        node: {
          id: '',
          addr: ''
        },
        ownerName: '',
        region: {
          name: ''
        }
      },
      // 设备状态
      creatTypeNum: {
        0: '未投放',
        1: '运营',
        3: '撤机'
      },
      // 策略选择的数组--渲染
      policyList: [],
      // 批量操作的数组值。需上传
      moreSelect: [],
      // 策略选择的值
      policyValue: ''
    }
  },
  created() {
    this.fetchEquipmentList(this.equipmentInfoParams)
  },
  methods: {
    async fetchEquipmentList(data) {
      try {
        // 获取设备列表
        const res = await searchEquipmentAPI(data)
        this.equipmentInfo = res.data
        // console.log(res.data)
        // 点位
        const res2 = await nodeSearchAPI({ ...this.equipmentInfoParams, pageSize: 1000 })
        this.nodeIdList = res2.data.currentPageRecords
        // 策略
        const res3 = await getPolicyAPI()
        this.policyList = res3.data
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 搜索框事件
    receiveInfo(value) {
      if (this.innerCode !== value) {
        this.innerCode = value
        this.equipmentInfoParams.pageIndex = 1
        this.fetchEquipmentList({ ...this.equipmentInfoParams, innerCode: this.innerCode })
      }
    },
    // 货道
    resource(row) {
      this.$bus.$emit('goodsChannelFn', row)
    },
    // 策略
    async policy(row) {
      const { data } = await policySearchAPI(row.innerCode)
      if (!data) {
        this.moreSelect = [row.innerCode]
        this.moreOperation()
      } else {
        this.policyDetails = {
          innerCode: data.innerCode,
          policyName: data.policyName,
          discount: data.discount,
          policyId: data.policyId
        }
        this.dialogVisiblePolicy.dialogVisible = true
      }
    },
    // 取消策略
    async canclePolicy() {
      try {
        await cancelPolicyAPI(this.policyDetails.innerCode, this.policyDetails.policyId)
        this.$message({
          type: 'success',
          message: '取消成功',
          offset: 75
        })
        this.dialogVisiblePolicy.dialogVisible = false
        this.fetchEquipmentList(this.equipmentInfoParams)
      } catch (error) {
        this.$message({
          type: 'error',
          message: error.response.data,
          offset: 75
        })
      }
    },
    // 修改
    async editInfo(row) {
      this.policyEdit = {
        id: row.id,
        innerCode: row.innerCode,
        lastSupplyTime: row.lastSupplyTime,
        type: {
          name: row.type.name,
          channelMaxCapacity: row.type.channelMaxCapacity
        },
        node: {
          id: row.node.id,
          addr: row.node.addr.split('-').at(-1)
        },
        ownerName: row.ownerName,
        region: {
          name: row.region.name
        }
      }
      this.dialogVisibleEdit.dialogVisible = true
    },
    // 批量操作选框选择的事件
    handleSelectionChange(selection) {
      this.moreSelect = []
      selection.forEach((item) => {
        this.moreSelect.push(item.innerCode)
      })
    },
    // 批量操作的弹框
    moreOperation() {
      if (this.moreSelect.length < 1) {
        return this.$message({
          type: 'warning',
          message: '请勾选售货机',
          offset: 75
        })
      }
      this.dialogVisibleOperation.dialogVisible = true
    },
    // 批量操作的确认事件
    async submitPolicy() {
      try {
        await applyPolicyAPI({ innerCodeList: this.moreSelect, policyId: this.policyValue })
        this.$message({
          type: 'success',
          message: '应用成功',
          offset: 75
        })
        this.fetchEquipmentList(this.equipmentInfoParams)
      } catch (error) {
        this.$message({
          type: 'error',
          message: error.response.data,
          offset: 75
        })
      } finally {
        this.dialogVisibleOperation.dialogVisible = false
      }
    },
    // 新建的弹框
    async newCreateEquit() {
      this.dialogVisibleCreate.dialogVisible = true
      // 获取点位和型号
      // 型号
      const res = await vmTypeAPI({ ...this.equipmentInfoParams, pageSize: 1000 })
      this.vmTypeList = res.data.currentPageRecords
    },
    // 新增弹窗关闭事件
    dialogCloseCreate() {
      this.$refs.ruleFormEdit.resetFields()
    },
    // 批量操作的关闭事件
    dialogCloseOperation() {
      this.policyValue = ''
    },
    // 新建的确认事件
    async submitForm() {
      try {
        await addEquipmentAPI({
          ...this.ruleFormEquip,
          createUserId: this.createUserId
        })
        this.dialogVisibleCreate.dialogVisible = false
        this.$message({
          type: 'success',
          message: '新增成功',
          offset: 75
        })
      } catch (error) {
        this.$message({
          type: 'error',
          message: error.response.data,
          offset: 75
        })
        return Promise.reject(error)
      }
    },
    // 修改事件的确认
    async submitEdit() {
      try {
        await repairPolicyNodeAPI(this.policyEdit.id, this.policyEdit.node.id)
        this.$message({
          type: 'success',
          message: '修改成功',
          offset: 75
        })
        this.dialogVisibleEdit.dialogVisible = false
      } catch (error) {
        this.$message({
          type: 'error',
          message: error.response.data,
          offset: 75
        })
      }
    },
    // 刷新页面
    refreshPage() {
      console.log(1)
      this.fetchEquipmentList(this.equipmentInfoParams)
    }
  },
  watch: {
    equipmentInfoParams: {
      handler() {
        this.fetchEquipmentList({ ...this.equipmentInfoParams, innerCode: this.innerCode })
      },
      deep: true
    }
  }
}
</script>
<style lang="less" scoped>
.equipment {
  .list {
    .el-col {
      margin-bottom: 20px;
    }
    /deep/.el-table th.el-table__cell {
      background-color: rgb(243, 246, 251);
    }
    /deep/tr.el-table__row {
      height: 45px !important;
    }

    /deep/.el-table td.el-table__cell {
      border: none;
      height: 0px;
      padding: 0;
      .el-button {
        height: 30px;
        line-height: 1px;
        margin: 10px 0 10px 10px;
        width: 80px;
      }
    }
    /deep/.el-table th.el-table__cell.is-leaf {
      border: none;
    }
    /deep/.el-button--warning {
      background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
      text-align: center;
      .icon-jiahao:before {
        content: '\e726';
        margin-right: 5px;
      }
    }
    /deep/.el-button--info {
      background-color: #fbf4f0 !important;
      border: none;
      color: #333;
    }
    /deep/.el-table::before {
      height: 0;
    }
  }
  .confirm {
    width: 100%;
    padding-left: 20%;
    /deep/.el-button--primary {
      background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
      border: none;
    }
  }
}
</style>
